//  IDVI 1.0 source copyright 1996 Garth A. Dickie
//
//  This source is free for non-commercial use.  No warranty, etc.
//  Please acknowledge reuse by including the line:
//
//  "Based in part on IDVI 1.0 source copyright 1996 Garth A. Dickie"
//
//  in your documentation and source code.  For commercial use or
//  distribution, please contact the author.  Please also send
//  questions, comments, bug reports, or fixes.
//
//  Best Regards,
//  Garth A. Dickie
//  dickie@elastic.avid.com

package ibook.v10.applets.colorchange;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class ColorChangeApplet extends Applet implements Runnable {
    private int     delay = 1500;
    private Color   color = Color.green;
    private Random  random = new Random( );

    public void init( ) {
        try {
            delay = Integer.parseInt( getParameter( "delay" ));
        } catch( NumberFormatException e ) {
        }
    }

    private Thread thread;
    private boolean running = false;

    public synchronized void start( ) {
        running = true;

        if( thread == null ) {
            thread = new Thread( this );
            thread.start( );
        } else
            notifyAll( );
    }

    public synchronized void stop( ) {
        running = false;
    }

    public synchronized void destroy( ) {
        thread.stop( );
        thread = null;
    }

    public void paint( Graphics g ) {
        g.setColor( color );
        g.fillRect( 0, 0, size( ).width, size( ).height );
    }

    public void update( Graphics g ) {
        paint( g );
    }




    public void run( ) {
        while( true ) {
            waitChangeTime( );
            change( );
        }
    }

    private synchronized void waitChangeTime( ) {
        try {
            thread.sleep( delay );
        } catch( InterruptedException e ) {
        }

        while( ! running )
            try {
                wait( );
            } catch( InterruptedException e ) {
            }
    }

    private void change( ) {
        color = new Color( random.nextInt( ));
        repaint( 25 );
    }
}
